package me.zhengjie.modules.workorder.service.impl;

import me.zhengjie.modules.customer.domain.TCustomerInfo;
import me.zhengjie.modules.customer.repository.TCustomerInfoRepository;
import me.zhengjie.modules.system.common.EnumWorkorderSource;
import me.zhengjie.modules.system.common.EnumWorkorderStatus;
import me.zhengjie.modules.workorder.domain.TTasks;
import me.zhengjie.modules.workorder.domain.TWorkOrder;
import me.zhengjie.utils.*;
import me.zhengjie.modules.workorder.repository.TTasksRepository;
import me.zhengjie.modules.workorder.repository.TWorkOrderRepository;
import me.zhengjie.modules.workorder.service.TTasksService;
import me.zhengjie.modules.workorder.service.TWorkOrderService;
import me.zhengjie.modules.workorder.service.dto.TAccidentDTO;
import me.zhengjie.modules.workorder.service.dto.TAccidentQueryCriteria;
import me.zhengjie.modules.workorder.service.dto.TTasksDTO;
import me.zhengjie.modules.workorder.service.dto.TTasksQueryCriteria;
import me.zhengjie.modules.workorder.service.mapper.TTasksMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.hutool.core.collection.CollectionUtil;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

/**
* @author zcw
* @date 2019-08-10
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TTasksServiceImpl implements TTasksService {

    @Autowired
    private TTasksRepository tTasksRepository;

    @Autowired
    private TTasksMapper tTasksMapper;
    
    @Autowired
    private TWorkOrderService tWorkOrderService;
    
    @Autowired
    private TWorkOrderRepository tWorkOrderRepository;

    @Autowired
    private TCustomerInfoRepository tCustomerInfoRepository;

    @SuppressWarnings("unchecked")
	@Override
    public Object queryAll(TTasksQueryCriteria criteria, Pageable pageable){
        Page<TTasks> page = tTasksRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        Page<TTasksDTO> pageDto = page.map(tTasksMapper::toDto);
        List<TTasksDTO> dtos = pageDto.getContent();
        if(CollectionUtil.isNotEmpty(dtos)) {
        	for(TTasksDTO dto:dtos) {
        		List<TWorkOrder> orders = tWorkOrderRepository.findOrderByOrderSource(2,dto.getId());
        		if(CollectionUtil.isNotEmpty(orders)) {
                    TWorkOrder order = orders.get(0);
                    dto.setOrder(orders.get(0));
                    if(order.getAddriveTime() == null && dto.getArriveTime() != null ) {  //如果预约时间为空,已故障单的时间填入,用于展示
                        order.setAddriveTime(new Timestamp(dto.getArriveTime().getTime()));
                    }
        			dto.setOrder(order);
        		}
        	}
        }
        return PageUtil.toPage(pageDto);
    }

    @SuppressWarnings("unchecked")
	@Override
    public Object queryAll(TTasksQueryCriteria criteria){
        return tTasksMapper.toDto(tTasksRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public TTasksDTO findById(Long id) {
        Optional<TTasks> tTasks = tTasksRepository.findById(id);
        ValidationUtil.isNull(tTasks,"TTasks","id",id);
        return tTasksMapper.toDto(tTasks.get());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TTasksDTO create(TTasks resources) {
    	resources.setInputOperator(SecurityUtils.getName());
    	resources.setInputTime(new Timestamp(System.currentTimeMillis()));
        resources.setState(EnumWorkorderStatus.CREATED.getValue());
    	TTasksDTO tTasksDTO = tTasksMapper.toDto(tTasksRepository.save(resources));

    	TWorkOrder order = new TWorkOrder();
    	order.setSourceId(tTasksDTO.getId());
        order.setCustomerId(tTasksDTO.getCustomerId());
        order.setCustomerName(tTasksDTO.getCustomerName());
    	order.setOrderSource(EnumWorkorderSource.ENUM_WORKORDER_SOURCE_TASK.getValue());
        order.setTaskAddr(resources.getTaskAddr());  //地址冗余
    	tWorkOrderService.create(order);
        return tTasksDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(List<TTasks> tasksList) {
        List<TWorkOrder> workOrderList = new ArrayList<>();
        for(TTasks resources: tasksList) {
            resources.setInputOperator(SecurityUtils.getName());
            resources.setInputTime(new Timestamp(System.currentTimeMillis()));
            resources.setState(EnumWorkorderStatus.CREATED.getValue());
            TTasks t = tTasksRepository.save(resources);

            TWorkOrder order = new TWorkOrder();
            order.setSourceId(t.getId());
            order.setCustomerId(t.getCustomerId());
            order.setCustomerName(t.getCustomerName());
            order.setOrderSource(EnumWorkorderSource.ENUM_WORKORDER_SOURCE_TASK.getValue());
            order.setTaskAddr(resources.getTaskAddr());  //地址冗余
            workOrderList.add(order);
        }
        tWorkOrderService.create(workOrderList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TTasks resources) {
        Optional<TTasks> optionalTTasks = tTasksRepository.findById(resources.getId());
        ValidationUtil.isNull( optionalTTasks,"TTasks","id",resources.getId());

        TTasks tTasks = optionalTTasks.get();
        resources.setId(tTasks.getId());
        tTasksRepository.save(resources);

        if(!StringUtils.isEmpty(tTasks.getTaskAddr()) && !StringUtils.isEmpty(resources.getTaskAddr()) &&
                !tTasks.getTaskAddr().trim().equals(resources.getTaskAddr().trim())) {
            List<TWorkOrder> orderList = tWorkOrderRepository.findOrderByOrderSource(EnumWorkorderSource.ENUM_WORKORDER_SOURCE_TASK.getValue(),tTasks.getId());
            for(TWorkOrder order: orderList) {
                order.setTaskAddr(resources.getTaskAddr());
                tWorkOrderRepository.saveAndFlush(order);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        tTasksRepository.deleteById(id);
    }

	@Override
	public Object queryAllWithOrder(TAccidentQueryCriteria criteria) {
		return tTasksMapper.toDto(tTasksRepository.findTAccidentWithOrder());
	}
}